import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { getTimeStamp } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
const expireTime = 3600

function isCheckTime() {
  return (Date.now() - getTimeStamp()) / 1000 > expireTime
}
// 添加请求拦截器
service.interceptors.request.use(function(config) {
  // 在发送请求之前做些什么
  if (store.state.user.token) {
    if (isCheckTime()) {
      // token过期
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token过期'))
    }
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
}, function(error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use(function(response) {
  if (!response.data.success) return Promise.reject(new Error('登录失败'))
  return response
}, function(error) {
  // token过期 401
  if (error.response.status === 401 && error.response.data.code) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  return Promise.reject(error)
})

export default service
